<script setup lang='ts' name="product-detail">
import Footer from '@/pages/footer/footer.vue'
import AddCar from '@/pages/product-preview/component/add-car.vue'
import Breadcrumb from '@/pages/product-preview/component/breadcrumb.vue'
import Tabs from '@/pages/product-preview/component/tabs.vue'
import { useGetHomeProductDetail } from '@fl/api/man-api'
import { cloneDeep } from 'lodash-es'
import { computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'

const catPath = ref<any>([])

const route = useRoute()
const router = useRouter()
const params = computed(() => ({
    ...route.query,
}))

const res = useGetHomeProductDetail(params.value.id)

const formData = computed(() => ({ ...res.data.value }))

// 类目记录
const categoryList = computed(() => {
    return formData.value?.categoryList ?? []
})

const isNoData = computed(() => {
    return JSON.stringify(formData.value) === '{}' || !formData.value
})

function getItem(params: any) {
    const item = cloneDeep(params)
    Reflect.deleteProperty(item, 'children')
    return item
}

function treeToArr(tree) {
    const flatData: any = []

    function flatten(node: any) {
        const item = getItem(node)
        flatData.push(item)

        if (node.children) {
            flatten(node.children[0])
        }
    }

    flatten(tree[0])

    return flatData
}

function clickHandle(item: any) {
    router.push({
        path: '/search',
        query: {
            ...item,
        },
    })
}

watchEffect(() => {
    if (categoryList.value && categoryList.value.length) {
        catPath.value = treeToArr(categoryList.value)
    }
})
</script>

<template>
    <div class="mx-auto mb-40 w-1300">
        <template v-if="!isNoData">
            <Breadcrumb :data="catPath"
                        @click-handle="clickHandle"
            />

            <AddCar :data="formData"
                    class="mt-60"
            />

            <Tabs :data="formData" />
        </template>

        <el-empty v-else
                  :image-size="200"
        />
    </div>

    <Footer />
</template>

<style lang="less" scoped>

</style>
